from django.http import JsonResponse
from django.db import connection
import json,requests
from rest_framework.decorators import api_view
from buildapi.models import BuildingInfo
from guestapi.models import GuestInfo
from HIKapi.models import HikInfo
from HIKapi.models import EzvizInfo
# Create your views here.


@api_view(['POST'])
def dispatcher(request):  

    # try:
    if request.user.is_authenticated:   # 验证Token是否正确
        if request.user.is_active:
            if request.method == 'GET':
                request.params = request.GET

            # POST/PUT/DELETE 请求 参数 从 request 对象的 body 属性中获取
            elif request.method in ['POST','PUT','DELETE']:
                # 根据接口，POST/PUT/DELETE 请求的消息体都是 json格式
                request.params = json.loads(request.body)


            # 根据不同的action分派给不同的函数进行处理
            action = request.params['action']
            if action == 'add':
                return Hik_add(request)
            elif action == 'del':
                return Hik_del(request)
            elif action == 'add_door':
                return Hik_add_door(request)
            elif action == 'del_door':
                return Hik_del_door(request)
            elif action == 'open_door':
                return Hik_open_door(request)
            elif action == 'get_group_list':
                return Hik_get_group_list(request)
            elif action == 'get_group':
                return Hik_get_group(request)
            elif action == 'list':
                return Hik_list(request)
            elif action == 'add_ezviz':
                return add_ezviz(request)
            elif action == 'list_ezviz':
                return list_ezviz(request)
            elif action == 'del_ezviz':
                return del_ezviz(request)

            else:
                return JsonResponse({'ret': 1, 'msg': '不支持该类型http请求'})
    else:
        return JsonResponse({'ret': 2, "msg": "token验证失败"})


def add_ezviz(request):
    data = json.loads(request.body)
    openid = data['openid']
    appkey = data['appkey']
    zone_id = data['zone_id']
    secret = data['secret']
    ezviz_name = data['ezviz_name']
    deviceserial = data['deviceserial']
    EzvizInfo.objects.create(
        openid = openid,
        ezviz_name = ezviz_name,
        zone_id = zone_id,
        appkey = appkey,
        secret = secret,
        deviceserial = deviceserial
        )
    return JsonResponse({'ret':0})


def list_ezviz(request):
    data = json.loads(request.body)
    openid = data['openid']
    zone_id = data['zone_id']
    index = EzvizInfo.objects.filter(openid=openid,zone_id=zone_id).values()
    count = EzvizInfo.objects.filter(openid=openid).count()
    return JsonResponse({'ret':0,'data':list(index),'count':count})


def del_ezviz(request):
    data = json.loads(request.body)
    deviceserial = data['deviceserial']
    index = EzvizInfo.objects.get(deviceserial=deviceserial)
    index.delete()
    return JsonResponse({'ret':0})


def Hik_list(request):
    try:
        data = json.loads(request.body)
        list_type = data['list_type']
        openid = data['openid']
        if list_type == 0:
            page_max = int(data['page_max'])
            page = int(data['page'])
            index = HikInfo.objects.filter(openid=openid).values().order_by('id')[page_max*page-page_max:page_max*page]
            count = HikInfo.objects.filter(openid=openid).count()
        elif list_type == 1:
            about_id = data['about_id']
            index = HikInfo.objects.filter(openid=openid,about_id=about_id).values()
            count = HikInfo.objects.filter(openid=openid).count()

        return JsonResponse({'ret':0,'data':list(index),'count':count})
    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "列表获取失败，发生异常:{}".format(e)
            })

def Hik_add(request):
    data = json.loads(request.body)
    try:
        user_mode = data['user_mode']
        if user_mode == 0:
            building_id = data['building_id']
            guest_id = data['guest_id']
            face = data['face']
            guest = GuestInfo.objects.filter(guest_id=guest_id).values()
            guest_index = list(guest)[0]
            hik = BuildingInfo.objects.filter(building_id=building_id).values()
            hik_index = list(hik)[0]

            # 开始hik流程
            token = get_token()
            #构建header
            form_header = {"Authorization": "Bearer {}".format(token),"Content-Type": "application/json"}

            # 删除原有人员
            requests.post('https://api2.hik-cloud.com/api/v1/open/basic/persons/delete?employeeNo={}'.format(guest_id),headers=form_header)

            #构建data
            form_data = {"employeeNo": "{}".format(guest_id), 
                        "personName": "{}".format(guest_index['guest_name']),
                        "validBeginTime": "{}T00:00:59+08:00".format(guest_index['guest_date1']),
                        "validEndTime": "{}T00:00:59+08:00".format(guest_index['guest_date2']),
                        "faceImageBase64": "{}".format(face),
                        "personType":"normal"}

            #新增人员
            create = requests.post('https://api2.hik-cloud.com/api/v1/open/basic/persons/create', data=json.dumps(form_data),headers=form_header)
            create_index = create.json()
            if create_index['code'] != 200:
                return JsonResponse({
                    "ret": 2,
                    "msg": create_index['message']
                })

            #groupid
            groupid = hik_index['building_about_groupid']
            group_data = {
                    "groupId": "{}".format(groupid), 
                    "employeeNos": ["{}".format(guest_id)]}

            #人员绑定权限组
            index = requests.post('https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/actions/addPersons', data=json.dumps(group_data),headers=form_header)
            
            hik_index = index.json()
            
            if hik_index['code'] != 200:
                return JsonResponse({
                    'ret': 2,
                    'msg': hik_index['message']
                })
            return JsonResponse({'ret':0,'msg':hik_index['message']})

        if user_mode == 1:
            openid = data['openid']
            guest_id = data['guest_id']
            face = data['face']
            #可能有多个设备
            if HikInfo.objects.filter(openid=openid).exists():
                hik = HikInfo.objects.filter(openid=openid).values('groupid')
                hik_data = list(hik)[0]
            else:
                return JsonResponse({
                    'ret': 1,
                    'msg': "未找到关联设备"
                })

            guest = GuestInfo.objects.get(guest_id=guest_id)
            # 开始hik流程
            token = get_token()
            #构建header
            form_header = {"Authorization": "Bearer {}".format(token),"Content-Type": "application/json"}

            # 删除原有人员
            requests.post('https://api2.hik-cloud.com/api/v1/open/basic/persons/delete?employeeNo={}'.format(guest_id),headers=form_header)

            #构建data
            form_data = {"employeeNo": "{}".format(guest_id), 
                        "personName": "{}".format(guest.guest_name),
                        "validBeginTime": "{}T00:00:59+08:00".format(guest.guest_date1),
                        "validEndTime": "{}T00:00:59+08:00".format(guest.guest_date2),
                        "faceImageBase64": "{}".format(face),
                        "personType":"normal"}

            #新增人员
            create = requests.post('https://api2.hik-cloud.com/api/v1/open/basic/persons/create', data=json.dumps(form_data),headers=form_header)
            create_index = create.json()
            if create_index['code'] != 200:
                guest.guest_face_type = 0
                guest.save()
                return JsonResponse({
                    'ret': 2,
                    'msg': create_index['message']
                })
            else:
                guest.guest_face_type = 1
                guest.save()

            #groupid
            groupid = hik_data['groupid']
            group_data = {
                    "groupId": "{}".format(groupid), 
                    "employeeNos": ["{}".format(guest_id)]}

            #人员绑定权限组
            index = requests.post('https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/actions/addPersons', data=json.dumps(group_data),headers=form_header)
            hik_index = index.json()
            
            if hik_index['code'] != 200:
                guest.guest_face_type = 0
                guest.save()
                return JsonResponse({
                    'ret': 2,
                    'msg': hik_index['message']
                })
            else:
                guest.guest_face_type = 1
                guest.save()

            return JsonResponse({'ret':0,'data':index.json()})

    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "人员添加失败，发生异常:{}".format(e)
            })


def Hik_del(request):
    try:
        data = json.loads(request.body)  
        guest_id = data['guest_id']

        token = get_token()
        #构建header
        form_header = {"Authorization": "Bearer {}".format(token)}

        index = requests.post('https://api2.hik-cloud.com/api/v1/open/basic/persons/delete?employeeNo={}'.format(guest_id),headers=form_header)
        index_data = index.json()
        
        return JsonResponse({'ret':0,'msg':index_data['message']})

    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "人员删除失败，发生异常:{}".format(e)
            })


def Hik_get_group_list(request):
    try:
        data = json.loads(request.body)  
        pageNo = data['pageNo']
        pageSize = data['pageSize']

        token = get_token()
        #构建header
        form_header = {"Authorization": "Bearer {}".format(token),"Content-Type": "application/json"}

        group_data = {
            "pageNo": pageNo,
            "pageSize": pageSize
        }

        index = requests.post('https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/actions/page', data=json.dumps(group_data),headers=form_header)

        return JsonResponse(index.json())

    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "发生异常:{}".format(e)
            })


def Hik_get_group(request):
    try:
        data = json.loads(request.body)  
        pageNo = data['pageNo']
        pageSize = data['pageSize']
        building_id = data['building_id']

        bre = BuildingInfo.objects.get(building_id=building_id)

        token = get_token()
        #构建header
        form_header = {"Authorization": "Bearer {}".format(token),"Content-Type": "application/json"}

        group_data = {
            "pageNo": pageNo,
            "pageSize": pageSize,
            "groupId": bre.building_about_groupid
        }

        index = requests.post('https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/actions/getEmployeeNos', data=json.dumps(group_data),headers=form_header)

        return JsonResponse(index.json())

    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "发生异常:{}".format(e)
            })


def Hik_add_door(request):
    data = json.loads(request.body) 
    cursor = connection.cursor()
    try:
        user_mode = data['user_mode']
        if user_mode == 0:
            building_about_door = data['building_about_door']
            building_id = data['building_id']
            door = BuildingInfo.objects.filter(building_id=building_id).values()
            door_count = BuildingInfo.objects.filter(building_about_door=building_about_door).count()
            door_index = list(door)[0]

            if door_index['building_about_door'] and door_index['building_about_groupid'] is not None:
                return JsonResponse({
                    'ret': 1,
                    'msg': "请先删除原有门禁设备再新增"
                })
            if door_count > 0:
                return JsonResponse({
                    'ret': 1,
                    'msg': "该门禁设备已存在"
                })
            else:
                # 开始hik流程
                token = get_token()
                #构建header
                form_header = {"Authorization": "Bearer {}".format(token),"Content-Type": "application/json"}

                #构建data
                form_data = {"groupName": "{}".format(building_id)}

                #新增权限组
                create = requests.post('https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/create', data=json.dumps(form_data),headers=form_header)
                create_index = create.json()

                #保存groupid
                cursor.execute(" UPDATE building_info SET building_about_groupid = '{}' , building_about_door = '{}' WHERE building_id = '{}' ".format(create_index['data']['groupId'],building_about_door,building_id))
                
                groupid = create_index['data']['groupId']
                group_data = {
                        "groupId": "{}".format(groupid), 
                        "checkCapability": True,
                        "deviceSerials": ["{}".format(building_about_door)]}
                #权限组绑定设备
                index = requests.post('https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/actions/addDevices', data=json.dumps(group_data),headers=form_header)
                index_data = index.json()
                return JsonResponse({'ret':0,'msg':index_data['message']})
        elif user_mode == 1:
            door_id = data['door_id']
            openid = data['openid']
            groupid = data['groupid']
            door_name = data['door_name']
            about_id = data['about_id']

            if HikInfo.objects.filter(door_id=door_id).exists():
                return JsonResponse({'ret':1,'msg': "该门禁设备已存在"})
            elif HikInfo.objects.filter(openid=openid,door_name=door_name).exists():
                return JsonResponse({'ret':1,'msg': "该门禁名称已存在"})   
            else:
                # 开始hik流程
                token = get_token()
                #构建header
                form_header = {"Authorization": "Bearer {}".format(token),"Content-Type": "application/json"}

                group_data = {
                        "groupId": "{}".format(groupid),
                        "checkCapability": True,
                        "deviceSerials": ["{}".format(door_id)]}
                #权限组绑定设备
                index = requests.post('https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/actions/addDevices', data=json.dumps(group_data),headers=form_header)
                hik_index = index.json()

                if hik_index['code'] != 200 :
                    return JsonResponse({'ret':2,'msg': hik_index['message']})
                
                build = BuildingInfo.objects.get(building_id=about_id)

                HikInfo.objects.create(
                    openid = openid,
                    door_id = door_id,
                    groupid = groupid,
                    door_name = door_name,
                    about_id = about_id,
                    about_name = build.building_nbr
                )

                return JsonResponse({'ret':0,'msg': hik_index['message']})


    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "门禁添加失败，发生异常:{}".format(e)
            })


def Hik_del_door(request):
    data = json.loads(request.body) 
    cursor = connection.cursor()
    try:
        user_mode = data['user_mode']
        openid = data['openid']
        if user_mode == 0:
            data = json.loads(request.body)  
            building_id = data['building_id']
            door = BuildingInfo.objects.filter(openid=openid,building_id=building_id).values()
            door_index = list(door)[0]

            token = get_token()
            #构建header
            form_header = {"Authorization": "Bearer {}".format(token)}

            index = requests.post('https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/delete?groupId={}'.format(door_index['building_about_groupid']),headers=form_header)
            index_data = index.json()
            cursor.execute(" UPDATE building_info SET building_about_groupid = NULL , building_about_door = NULL WHERE building_id = '{}' ".format(building_id))
            
            return JsonResponse({'ret':0,'msg':index_data['message']})

        if user_mode == 1:
            door_name = data['door_name']

            if HikInfo.objects.filter(openid=openid,door_name=door_name).exists():
                user_index = HikInfo.objects.get(openid=openid,door_name=door_name)
            else:
                return JsonResponse({
                'ret': 1,
                'msg': "该门禁不存在"
            })

            token = get_token()
            #构建header
            form_header = {"Authorization": "Bearer {}".format(token),"Content-Type": "application/json"}

            from_data = {
                "groupId": "{}".format(user_index.groupid),
                "deviceSerials": ["{}".format(user_index.door_id)]
            }

            index = requests.post('https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/actions/removeDevices', data=json.dumps(from_data),headers=form_header)
            hik_index = index.json()

            if hik_index['code'] != 200 :
                return JsonResponse({'ret':2,'msg': hik_index['message']})

            user_index.delete()
            
            return JsonResponse({'ret':0,'msg': hik_index['message']})

    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "门禁删除失败，发生异常:{}".format(e)
            })


def Hik_open_door(request):
    data = json.loads(request.body)
    try:
        user_mode = data['user_mode']
        if user_mode == 0:
            building_id = data['building_id']
            door = BuildingInfo.objects.filter(building_id=building_id).values()
            door_index = list(door)[0]
            building_about_door = door_index['building_about_door']
            # 开始hik流程
            token = get_token()
            #构建header
            form_header = {"Authorization": "Bearer {}".format(token),"Content-Type": "application/json"}

            #构建data
            form_data = {"deviceSerial": "{}".format(building_about_door)}

            #开门
            create = requests.post('https://api2.hik-cloud.com/api/v1/open/accessControl/remoteControl/actions/open', data=json.dumps(form_data),headers=form_header)
            create_index = create.json()
            return JsonResponse({'ret':0,'msg':create_index['message']})
        if user_mode == 1:
            door_name = data['door_name']
            openid = data['openid']
            user_index = HikInfo.objects.get(openid=openid,door_name=door_name)
            # 开始hik流程
            token = get_token()
            #构建header
            form_header = {"Authorization": "Bearer {}".format(token),"Content-Type": "application/json"}

            #构建data
            form_data = {"deviceSerial": "{}".format(user_index.door_id)}

            #开门
            create = requests.post('https://api2.hik-cloud.com/api/v1/open/accessControl/remoteControl/actions/open', data=json.dumps(form_data),headers=form_header)
            create_index = create.json()
            if create_index['code'] != 200 :
                return JsonResponse({'ret':2,'msg': create_index['message']})
            else:
                return JsonResponse({'ret':0,'msg': create_index['message']})
    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "开门失败，发生异常:{}".format(e)
            })


def get_token():
    # 开始hik流程
    token_data = {"client_id" : "3a3660ab145c499b98cbc776f461b559",
    "client_secret": '1c40b846c4584974abb590be9c6a00b0',
    "grant_type" : "client_credentials"}
    # 获取token
    response = requests.post('https://api2.hik-cloud.com/oauth/token', data=token_data)
    res = response.json()
    token = res['access_token']
    return(token)